package com.wrupple.muba.catalogs.client.view.impl;

import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.view.client.HasData;
import com.wrupple.muba.catalogs.client.events.DataSelectionRequest;
import com.wrupple.muba.catalogs.client.view.BrowseView;
import com.wrupple.muba.catalogs.client.view.FilterToolbar;
import com.wrupple.muba.catalogs.client.view.GenericSelectionToolbar;
import com.wrupple.muba.catalogs.client.view.SelectionToolbar.SelectionRequestHandler;
import com.wrupple.muba.catalogs.client.widgets.impl.CatalogTheme;
import com.wrupple.muba.catalogs.client.widgets.impl.GenericSelectionToolbarImpl;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;

public class SimpleBrowseView<T extends JavaScriptObject> extends
		SimpleDataView<T> implements BrowseView<T> {
	
	
	private class SelectionRequestHandlerImpl implements
			SelectionRequestHandler {

		@Override
		public void onSelectionReques(DataSelectionRequest event) {
			event.setVisibleData(display.getVisibleItems());
		}

	}

	class CloseAndClearToolbar extends DataCallback<List<T>> {

		@Override
		public void execute() {
			selectionToolbar.clear();
			main.hideToolbar(selectionToolbar);
		}

	}
	
	
	
	protected GenericSelectionToolbar selectionToolbar;
	protected FilterToolbar filterView;

	public SimpleBrowseView(FilterToolbar filter, HasData<T> display,
			CatalogTheme theme) {
		super(display);
		selectionToolbar = new GenericSelectionToolbarImpl(theme);
		selectionToolbar
				.addSelectionRequestHandler(new SelectionRequestHandlerImpl());

		this.filterView = filter;

		main.addToolbar(filter);
	}

	@Override
	public void addToSelection(T entry) {
		CatalogEntry value = entry.cast();
		this.selectionToolbar.addToSelection(value);
	}

	@Override
	public boolean isSelecting() {
		return main.isToolbarVisible(selectionToolbar);
	}

	public FilterToolbar getFilterView() {
		return filterView;
	}


	@Override
	public void startSelection(List<T> initialValues,
			StateTransition<List<T>> onDone) {
		StateTransition<List<T>> closeAndClearToolbar = new CloseAndClearToolbar();
		onDone.hook(closeAndClearToolbar);
		List values = initialValues;
		StateTransition back = onDone;
		selectionToolbar.start(values, back, null);
		main.showToolbar(selectionToolbar);
	}

}
